package com.example.redisdemo.service;

import com.alibaba.fastjson.JSON;
import com.example.redisdemo.configuration.RabbitConfig;
import com.example.redisdemo.enums.RabbitEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author hexinglin
 * @created 2021-08-11 14:59
 **/
@Component
@Slf4j
public class Sender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String messageString){
        CorrelationData data = new CorrelationData(UUID.randomUUID().toString());
        Map<String,String> map=new HashMap<>();
        map.put("key","hello："+messageString);
        try {
            Message message= MessageBuilder.withBody(JSON.toJSONString(map).getBytes("UTF-8")).setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN).build();
            rabbitTemplate.convertAndSend(RabbitConfig.DIRECT_EXCHANGE_NAME,RabbitConfig.BINGDING_KEY_TEST1,message,data);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
    public void send(String exchangeName,String routKey,String messageString){
        CorrelationData data = new CorrelationData(UUID.randomUUID().toString());
        Map<String,String> map=new HashMap<>();
        map.put("key","hello："+messageString);
        try {
            Message message= MessageBuilder.withBody(JSON.toJSONString(map).getBytes("UTF-8")).setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN).build();
            log.info("【mq发送的时间为：】,{}", LocalDateTime.now());

            rabbitTemplate.convertAndSend(exchangeName,routKey,message,data);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
